package com.carpedil.shirodemo.system.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.carpedil.shirodemo.common.exception.BizRuntimeException;
import com.carpedil.shirodemo.system.mapper.DeptMapper;
import com.carpedil.shirodemo.system.mapper.UserMapper;
import com.carpedil.shirodemo.system.model.Dept;
import com.carpedil.shirodemo.system.model.User;
import com.carpedil.shirodemo.system.service.IDeptService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * 服务实现类
 *
 * @author carpedil
 * @since 2021-01-05
 */
@Service
public class DeptServiceImpl extends ServiceImpl<DeptMapper, Dept> implements IDeptService {
  @Autowired private DeptMapper deptMapper;
  @Autowired private UserMapper userMapper;

  @Override
  public List<Dept> selectAllDeptTree() {
    return deptMapper.selectAllDeptTree();
  }

  @Override
  public List<Dept> getAllDeptTreeAndRoot() {
    List<Dept> depts = this.selectAllDeptTree();
    return addRootNode("导航目录", 0, depts);
  }

  @Override
  public List<Dept> getChildListByDeptId(Integer parentId) {
    return deptMapper.selectDeptById(parentId);
  }

  @Override
  @Transactional(rollbackFor = Exception.class)
  public void swapSort(Integer currentId, Integer swapId) {
    deptMapper.swap(currentId, swapId);
  }

  @Override
  @Transactional(rollbackFor = Exception.class)
  public void insert(Dept dept) {
    dept.setOrderNum(deptMapper.selectMaxOrderNum() + 1);
    this.save(dept);
  }

  @Override
  @Transactional(rollbackFor = Exception.class)
  public void deleteDeptById(Integer id) {
    List<User> users = userMapper.selectUserByDeptId(id);
    if (users.size() > 0) {
      throw new BizRuntimeException("该部门还有关联员工信息,不能删除");
    }
    deptMapper.deleteById(id);
  }

  @Override
  @Transactional(rollbackFor = Exception.class)
  public void updateDept(Dept dept) {
    deptMapper.updateById(dept);
  }

  private List<Dept> addRootNode(String rootName, int rootId, List<Dept> depts) {
    Dept dept = new Dept();
    dept.setDeptId(rootId);
    dept.setDeptName(rootName);
    dept.setChildren(depts);
    List<Dept> deptList = new ArrayList<>();
    deptList.add(dept);
    return deptList;
  }
}
